import store from "../store"
import { Message } from 'element-ui'
import {realUrlForSocket} from "@/api/ps_form"

import { getSid,getToken } from '@/utils/auth'

function getSocket (subject,message){
    if(typeof WebSocket=='undefined'){
        Message({message:"您的浏览器不支持WebSocket,请更换浏览器！",type:"warning"});
        return null;
    }
    let flag="flag_"+new Date().getTime()+parseInt((Math.random()+1)*1000,10)
    let url=getRealUrl(flag,subject);
    url=url.replace("https","ws").replace("http","ws");
    let websocket=new WebSocket(url)
    websocket.store=store;
    websocket.subject=subject;
    store.dispatch("business/setValue",{root:'__WebSocket',key:subject,value:{socket:websocket,flag:flag}});
    websocket.onmessage=(msg)=>{
        let s=JSON.parse(msg.data)
        if(s.result=='LOGON'){
            let $store=msg.target.store;
            setTimeout(function(){
                $store.dispatch("user/resetToken")
                $store.dispatch('tagsView/delAllViews', null, { root: true })
              },20)
            return;
        }
        if(s.subject==msg.target.subject)
        store.dispatch("business/setValue",{root:msg.target.subject,key:'socket_content',value:s.content});
        else if(s.subject=='SYSTEM'){
            console.log("websocket_system_data:"+msg.data)
        }
    }
    websocket.onclose=()=>{
        store.dispatch("business/setValue",{root:'__WebSocket',key:flag,value:undefined});
    }
    websocket.onopen=(e)=>{
        //打开后，发送第一个消息
        if(typeof message=='object'){
            message=JSON.stringify(message)
        }
        let msg={"subject":subject,"content":message,token:getToken(),_SID:getSid()};
        e.target.send(JSON.stringify(msg))
    }
    websocket.onerror=()=>{
        console.log("websocket发生了错误,标识为："+flag);
    }
  //  websocket.open();
    return websocket;
}
function getRealUrl(flag,subject){
    let url=realUrlForSocket(subject)+"/"+flag;
    let token=getToken();
    if(_.isEmpty(token)){
    store.dispatch("user/resetToken")
    store.dispatch('tagsView/delAllViews', null, { root: true })
    return ;
    }
    let sid=getSid();
    if(url.indexOf("token")==-1)
    url+="?"+"token="+token+"&_SID="+sid;
    if(url.indexOf("_VIEWER")==-1)
    url+='&_VIEWER=APP'
    if(url.indexOf("_PID")==-1){
        url+="&_PID="+getRandom();
    }
    if(!/^http/g.test(url)){
        let local=window.location
        url=local.protocol+"//"+local.host+"/"+url
    }
    return url;
  }
  function getRandom(){
    return new Date().getTime()+((1+Math.random())*1000).toFixed("2")+"";
  }
function sendMessage(message,subject){
    if(!subject){
        Message({message:"webSocket标识不能为空",type:"warning"});
       return;
    }
    let socket=store.state.business.__WebSocket==undefined?null:store.state.business.__WebSocket[subject];
    if(socket)socket=socket.socket;
    if(!socket||socket.readyState+""=="2"||socket.readyState+""=="3"){
        socket=getSocket(subject,message);
        if(socket==null)return;
        return;
    }
    if(typeof message=='object'){
        message=JSON.stringify(message)
    }
    let msg={"subject":subject,"content":message,token:getToken(),_SID:getSid()};
    socket.send(JSON.stringify(msg))
}
function closeSocket(subject){
    if(store.state.business.__WebSocket){
        let socketinfo=store.state.business.__WebSocket[subject];
        if(socketinfo && socketinfo.socket){
            socketinfo.socket.close()
        }
    }
}
export default{
    sendMessage,closeSocket
}
